<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .container {
        width: 90%;
        margin: 0 auto;
        position: relative;
        background-color: antiquewhite;
        margin-top: 50px;
      }
      .container img {
        position: absolute;
        transition: 0.3s;
      }
    </style>
  </head>
  <body>
    <div class="container"></div>

    <script>
      const container = document.querySelector(".container");

      let fragment = document.createDocumentFragment();
      let img_width = 220;

      function createImg() {
        for (let i = 1; i <= 12; i++) {
          let src = "../images/" + i + ".jpg";
          let img = document.createElement("img");
          img.src = src;
          img.width = img_width;
          // 每张图片加载完设置一下位置
          img.onload = setPositions;
          fragment.appendChild(img);
        }
        // 更好的性能，一次性加入dom
        container.appendChild(fragment);
      }
      createImg();
      //计算一共有多少列，以及每一列间的间隙
      function cal() {
        // 容器宽度
        let container_width = container.clientWidth;
        // 计算列的数量
        let columns = Math.floor(container_width / img_width);
        // 计算间隙
        let space_num = columns + 1; //间隙数量
        let left_space = container_width - columns * img_width; //剩余空间
        let space = left_space / space_num; //每个间隙的空间
        return {
          space,
          columns,
        };
      }
      // 设置图片位置
      function setPositions() {
        let info = cal();
        let next_tops = new Array(info.columns);
        next_tops.fill(0);
        for (let i = 0; i < container.children.length; i++) {
          let img = container.children[i];
          let min_top = Math.min.apply(null, next_tops);
          img.style.top = min_top + "px";
          //从最小的高度开始添加
          let index = next_tops.indexOf(min_top);
          next_tops[index] += img.height + info.space;
          // 计算横坐标
          let left = (index + 1) * info.space + index * img_width;
          img.style.left = left + "px";
        }
        // 获取最大高度
        let max = Math.max.apply(null, next_tops);
        container.style.height = max + "px";
      }
      let timer = null;
      window.onresize = function () {
        if (timer) {
          clearTimeout(timer);
        }

        timer = setTimeout(setPositions, 500);
      };
    </script>
  </body>
</html>
